<template>
	<view class="gy-upload-images">
	    <view class="gy-upload-images-item" v-for="(item,index) in props.modelValue" :key="index">
	        <image src="https://ainengli.meilianshuke.com/jkhx/patient/close-icon.png" class="gy-upload-images-del" @click.stop="removeFn(index)"></image>
	        <com-image :src="item" style="width: 100%;" @tap.stop="previewImageFn(item)" />
	    </view>
	    <view v-if="props.modelValue.length < props.maxlength" class="gy-upload-images-btn" @click.stop="chooseImageFn">
				<image src="https://ainengli.meilianshuke.com/jkhx/patient/plus.png" class="plus-icon" />
			</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		ref,
		computed,
		onMounted,
		getCurrentInstance
	} from "vue";

	import {
		batchUpload
	} from "@/request/apis/file.js";
import { upload } from "../../request/apis/file";

	const { proxy }: any = getCurrentInstance();

	const emits = defineEmits(["update:modelValue"]);

	const props = defineProps({
		modelValue: {
	        type: Array,
	        default: () => []
	    },
	    maxlength: {
	        type: Number,
			default: 9
	    },
		page: {
			type: Object as any
		},
		sizeLimit: {
			type: Number,
			default: 20
		}
	});

	function removeFn(index: number){
		let arr = JSON.parse(JSON.stringify(props.modelValue));
		arr.splice(index, 1);
		emits("update:modelValue", arr);
	}

	function previewImageFn(url: string) {
		uni.previewImage({
			current: url,
			urls: props.modelValue
		})
	}

	// 获取文件信息的辅助函数
	function getFileInfo(filePath: string): Promise<{ size: number }> {
		return new Promise((resolve, reject) => {
			uni.getFileInfo({
				filePath,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			});
		});
	}

	function chooseImageFn() {
    uni.setStorageSync("is-choose-location", 0);
    uni.chooseImage({
			count: countResidueFn(),
			success: async (res: any) => {
				if (res.errMsg !== "chooseImage:ok") return;
				uni.showLoading({
					title: '上传中',
					mask: true
				})
				
				const MAX_SIZE = props.sizeLimit * 1024 * 1024; // 大小限制
				const tempFilePaths = res.tempFilePaths;
				const validFiles = [];
					
				// 检查文件大小
				for (const filePath of tempFilePaths) {
					try {
						const fileInfo = await getFileInfo(filePath);
						if (fileInfo.size > MAX_SIZE) {
							uni.hideLoading();
							uni.showToast({
								title: `文件超过${props.sizeLimit}MB限制`,
								icon: 'none',
								duration: 3000
							});
						} else {
							validFiles.push(filePath);
						}
					} catch (error) {
						uni.hideLoading();
						console.error('获取文件信息失败:', error);
						proxy.utils.log.error(`获取文件信息失败: ${error.toString()}`);
					}
				}
				
				if (validFiles.length === 0) return;
				
				// 批量上传有效文件
				const uploadedUrls = [];
				const totalFiles = validFiles.length;
					
				for (let i = 0; i < validFiles.length; i++) {
					const filePath = validFiles[i];
					try {
						// 更新进度提示（显示当前第几个/总共几个）
						const progressCallback = (progress: number) => {
							const current = i + 1;
							if (progress < 100) {
								props.page?.loading.show(`上传中 (${current}/${totalFiles}): ${progress}%`);
							} else {
								props.page?.loading.show(`保存中 (${current}/${totalFiles})`);
							}
						};
						
						const result = await upload(filePath, progressCallback);
						uploadedUrls.push(result);
						uni.hideLoading();
					} catch (error) {
						uni.hideLoading();
						console.error('文件上传失败:', error);
						proxy.utils.log.error(`文件上传失败: ${error.toString()}`);
						// 可选：继续上传其他文件或中断
					}
				}
				
				// 更新数据
				if (uploadedUrls.length > 0) {
					let arr = JSON.parse(JSON.stringify(props.modelValue));
					arr = arr.concat(uploadedUrls);
					emits("update:modelValue", arr);
				}
			}
    });
	}

	function countResidueFn(){
		if(props.modelValue.length === 0){
			return props.maxlength;
		}else{
			if(props.modelValue.length < props.maxlength){
				return props.maxlength - props.modelValue.length;
			}else{
				return 0;
			}
		}
	}

</script>

<style lang="scss" scoped>
	.gy-upload-images{
	    display: grid;
	    grid-template-columns: repeat(4, 1fr);
	    gap: var(--gy-gap);
	    .gy-upload-images-btn{
	        height: calc((100vw - (var(--gy-gap) * 7)) / 4);
	        @include flex-center-center;
	        border: 1rpx solid #e5e6eb;
	        border-radius: 8rpx;
	        font-size: 54rpx;
	        color: var(--gy-text-color-placeholder);
					background: #fafafa;
					.plus-icon {
						width: 40rpx;
						height: 40rpx;
					}
	    }
	    .gy-upload-images-item{
	        height: calc((100vw - (var(--gy-gap) * 7)) / 4);
	        position: relative;
	        @include flex-center-center;
	        border-radius: 8rpx;
	        overflow: hidden;
	        .gy-upload-images-del{
	            position: absolute;
	            top: 0;
	            right: 0;
	            z-index: 1;
	            width: 36rpx;
							height: 32rpx;
	            // background-color: rgba(0, 0, 0, 0.8);
	            color: #ffffff;
	            font-size: 20rpx;
	            @include flex-center-center;
	            border-bottom-left-radius: var(--gy-border-radius-medium);
	        }
	    }
	}
</style>
